﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using BusinessLogic.ClassFactory;
using BusinessLogic.BusinessRules;
using DataAccess;
using Model;
using log4net;
using ValidateCommon;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using Common;

namespace RichECMS.ServerPages.SysManage
{
    public partial class AddSebSite : Util.BasePage.BasePage
    {
        private static readonly ILog objLog = LogManager.GetLogger(typeof(WebSite));
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (State.LoginUser.ManagerCompetence > (int)Utility.ManagerCompetence.Designer)
                {
                    Response.Write("您没有权限操作此页面");
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message.Replace("\r\n", ""));
                Response.End();
            }
        }

        /// <summary>
        /// 验证输入
        /// </summary>
        private bool ValidateValues()
        {
            bool bolIsValidate = true;
            if (this.txtTitle.Value.Trim().Length == 0)
            {
                Alert("请填写标题");
                bolIsValidate = false;
            }
            //if (!ParamAuth.IsNumber(this.txtIndexTemplateID.Value.Trim()))
            //{
            //    Alert("请填写网站首页模版ID");
            //    bolIsValidate = false;
            //}

            Regex re = new Regex(@"^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$", RegexOptions.IgnoreCase);
            if (!re.IsMatch(this.txtTitle.Value.Trim()))
            {
                Alert("您输入的网站路径里含有非法字符，请输入字母，数字 下划线的组合，下划线不能再开头或结尾");
                bolIsValidate = false;
            }

            using (WebSiteFactory objWebsiteFavtory = new WebSiteFactory())
            {
                BusinessLogic.BusinessRules.WebSite objWebSite = objWebsiteFavtory.CreatorBySql(" chvIssuePath='" + this.txtIssuePath.InnerText.Trim() + "'");
                if (objWebSite != null)
                {
                    Alert("您输入的网站路径已经被占用,请重新输入");
                    bolIsValidate = false;
                }
            }
            return bolIsValidate;
        }

        /// <summary>
        /// 提交网站SEO信息和系统配置信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SubmitBtnHander(object sender, ImageClickEventArgs e)
        {
            if (!ValidateValues())
            {
                return;
            }

            using (DBManager _DBManager = new DBManager())
            {
                try
                {
                    _DBManager.BeginTransaction();
                    //设定路径
                    string strRepleaceOld = "serverpages\\sysmanage\\AddSebSite.aspx".ToLower();
                    string strwebpath = Server.MapPath(Request.Path).ToLower().Replace(strRepleaceOld, "");

                    WebSiteFactory objFactory = new WebSiteFactory(_DBManager);
                    BusinessLogic.BusinessRules.WebSite objWebSite = objFactory.NewInstance();
                    objWebSite.DataItem.chvDescription = txtDescription.InnerText;
                    objWebSite.DataItem.chvKeyWords = txtKeyWords.InnerText;
                    objWebSite.DataItem.chvTitle = txtTitle.InnerText;
                    objWebSite.DataItem.chvName = txtTitle.InnerText;
                    objWebSite.DataItem.chvIssuePath = txtIssuePath.InnerText;
                    objWebSite.DataItem.chvWebUrl = txtWebUrl.InnerText;
                    objWebSite.DataItem.intTmplID = "-1";
                    objWebSite.DataItem.intLanguage = Convert.ToInt32(Utility.WebSiteLanguage.China);
                    objWebSite.DataItem.intWSState = Convert.ToInt32(Utility.WebSiteState.Use);
                    objWebSite.DataItem.intWebSiteLevel = Convert.ToInt32(Utility.WebSiteLevel.NoIndex);
                    objWebSite.Insert();

                    //初始化发布文件夹
                    if (!Directory.Exists(strwebpath + "news\\" + txtIssuePath.InnerText + "\\"))
                    {
                        Directory.CreateDirectory(strwebpath + "news\\" + txtIssuePath.InnerText + "\\");
                    }
                    if (!Directory.Exists(strwebpath + "news\\" + txtIssuePath.InnerText + "\\ahtml\\"))
                    {
                        Directory.CreateDirectory(strwebpath + "news\\" + txtIssuePath.InnerText + "\\ahtml\\");
                    }
                    if (!Directory.Exists(strwebpath + "news\\" + txtIssuePath.InnerText + "\\shtml\\"))
                    {
                        Directory.CreateDirectory(strwebpath + "news\\" + txtIssuePath.InnerText + "\\shtml\\");
                    }
                    if (!Directory.Exists(strwebpath + "news\\" + txtIssuePath.InnerText + "\\common\\"))
                    {
                        Directory.CreateDirectory(strwebpath + "news\\" + txtIssuePath.InnerText + "\\common\\");
                    }
                    //初始化模版文件夹
                    if (!Directory.Exists(strwebpath + "TemplateFile\\" + txtIssuePath.InnerText + "\\"))
                    {
                        Directory.CreateDirectory(strwebpath + "TemplateFile\\" + txtIssuePath.InnerText + "\\");
                    }
                    //设定上传文件夹
                    if (!Directory.Exists(strwebpath + "news\\" + txtIssuePath.InnerText + "\\Pcfiles\\"))
                    {
                        Directory.CreateDirectory(strwebpath + "news\\" + txtIssuePath.InnerText + "\\Pcfiles\\");
                    }
                    //设定默认预设图片
                    if (!File.Exists(strwebpath + "news\\" + txtIssuePath.InnerText + "\\Pcfiles\\default.jpg"))
                    {
                        if (File.Exists(Server.MapPath("~/") + "Pcfiles\\default.jpg"))
                        {
                            File.Copy(Server.MapPath("~/") + "Pcfiles\\default.jpg", strwebpath + "news\\" + txtIssuePath.InnerText + "\\Pcfiles\\default.jpg", true);
                        }
                    }

                    //设定默认模版
                    if (!File.Exists(strwebpath + "TemplateFile\\" + txtIssuePath.InnerText + "\\" + "index.html"))
                    {
                        File.Create(strwebpath + "TemplateFile\\" + txtIssuePath.InnerText + "\\" + "index.html");
                    }
                    if (!File.Exists(strwebpath + "TemplateFile\\" + txtIssuePath.InnerText + "\\" + "blank.html"))
                    {
                        File.Create(strwebpath + "TemplateFile\\" + txtIssuePath.InnerText + "\\" + "blank.html");
                    }
                    TemplateFactory objTemplateFactory = new TemplateFactory(_DBManager);
                    BusinessLogic.BusinessRules.Template objTemplate = objTemplateFactory.NewInstance();
                    objTemplate.DataItem.chvName = "首页";
                    objTemplate.DataItem.intType = Convert.ToInt32(Utility.TemplateType.WebSite);
                    objTemplate.DataItem.intWSID = objWebSite.DataItem.intWebSiteID;
                    objTemplate.DataItem.dtmInTime = DateTime.Now;
                    objTemplate.DataItem.intState = Convert.ToInt32(Utility.TemplateState.Use);
                    objTemplate.DataItem.chvPath = "index.html";
                    objTemplate.Insert();

                    //更新首页设置
                    objWebSite.DataItem.intTmplID = objTemplate.DataItem.intTemplateID.ToString();
                    objWebSite.Update();

                    //加入空白页面
                    //栏目页
                    objTemplate = objTemplateFactory.NewInstance();
                    objTemplate.DataItem.chvName = "空栏目页";
                    objTemplate.DataItem.intType = Convert.ToInt32(Utility.TemplateType.Section);
                    objTemplate.DataItem.intWSID = objWebSite.DataItem.intWebSiteID;
                    objTemplate.DataItem.dtmInTime = DateTime.Now;
                    objTemplate.DataItem.intState = Convert.ToInt32(Utility.TemplateState.Use);
                    objTemplate.DataItem.chvPath = "blank.html";
                    objTemplate.Insert();
                    //记录空栏目模版ID
                    int intBlankSectionTempID = objTemplate.DataItem.intTemplateID;

                    //文章页
                    objTemplate = objTemplateFactory.NewInstance();
                    objTemplate.DataItem.chvName = "空文章页";
                    objTemplate.DataItem.intType = Convert.ToInt32(Utility.TemplateType.Article);
                    objTemplate.DataItem.intWSID = objWebSite.DataItem.intWebSiteID;
                    objTemplate.DataItem.dtmInTime = DateTime.Now;
                    objTemplate.DataItem.intState = Convert.ToInt32(Utility.TemplateState.Use);
                    objTemplate.DataItem.chvPath = "blank.html";
                    objTemplate.Insert();
                    //记录空文章模版ID
                    int intBlankArticleTempID = objTemplate.DataItem.intTemplateID;

                    SystemVariableFactory objSystemVariableFactory = new SystemVariableFactory(_DBManager);
                    SystemVariable objSystemVariable = objSystemVariableFactory.NewInstance();

                    objSystemVariable.DataItem.intWSID = objWebSite.DataItem.intWebSiteID;
                    objSystemVariable.DataItem.chvIssuePath = txtIssuePath.InnerText;
                    objSystemVariable.DataItem.chvPicPath = txtIssuePath.InnerText;
                    objSystemVariable.DataItem.chvMiniPicPath = txtIssuePath.InnerText;
                    objSystemVariable.DataItem.chvTemplatePath = txtIssuePath.InnerText;
                    objSystemVariable.DataItem.chvWebUrl = txtWebUrl.InnerText;
                    objSystemVariable.DataItem.chvWebSiteName = objWebSite.DataItem.chvTitle;

                    State.LoginUser.IssuePath = strwebpath + "news\\" + objSystemVariable.DataItem.chvIssuePath;
                    State.LoginUser.MiniPicPath = strwebpath + "Pcfiles\\" + objSystemVariable.DataItem.chvMiniPicPath;
                    State.LoginUser.PicPath = strwebpath + "Pcfiles\\" + objSystemVariable.DataItem.chvPicPath;
                    State.LoginUser.WebUrl = objSystemVariable.DataItem.chvWebUrl;
                    State.LoginUser.TemplatePath = strwebpath + "TemplateFile\\" + objSystemVariable.DataItem.chvTemplatePath;
                    objSystemVariable.Insert();

                    //首次空数据库登录
                    UserManageInfoFactory objUserManageInfoFactory = new UserManageInfoFactory(_DBManager);
                    BusinessLogic.BusinessRules.UserManageInfo objUserManageInfo = objUserManageInfoFactory.NewInstance();
                    if (State.LoginUser.LoginName == "FirstSysadmin")
                    {
                        //管理员表
                        objUserManageInfo.DataItem.chvLoginName = "sysadmin";
                        objUserManageInfo.DataItem.chvLoginPsw = EncryptUtily.EncryptUtily.LoginEncrypt("1");
                        objUserManageInfo.DataItem.intWSID = objWebSite.DataItem.intWebSiteID;
                        objUserManageInfo.DataItem.dtmInTime = DateTime.Now;
                        objUserManageInfo.Insert();
                    }

                    UserWebRelationFactory objUserWebRelationFactory = new UserWebRelationFactory(_DBManager);
                    UserWebRelation objUserWebRelation = objUserWebRelationFactory.NewInstance();
                    if (State.LoginUser.LoginName == "FirstSysadmin")
                    {
                        objUserWebRelation.DataItem.chvLoginName = "sysadmin";
                        objUserWebRelation.DataItem.chvUserName = "sysadmin";
                        objUserWebRelation.DataItem.intManager = (int)Utility.ManagerCompetence.SysAdmin;
                        objUserWebRelation.DataItem.intUserID = objUserManageInfo.DataItem.intUserID;
                    }
                    else
                    {
                        objUserWebRelation.DataItem.chvLoginName = State.LoginUser.LoginName;
                        objUserWebRelation.DataItem.chvUserName = State.LoginUser.StrName;
                        objUserWebRelation.DataItem.intManager = State.LoginUser.ManagerCompetence;
                        objUserWebRelation.DataItem.intUserID = State.LoginUser.UserID;
                    }
                    objUserWebRelation.DataItem.chvPermissions = "";
                    objUserWebRelation.DataItem.chvPermissionsText = "";
                    objUserWebRelation.DataItem.intState = Convert.ToInt32(Utility.WebSiteState.Use);
                    objUserWebRelation.DataItem.intWSID = objWebSite.DataItem.intWebSiteID;
                    objUserWebRelation.DataItem.dtmDateInTime = DateTime.Now;
                    objUserWebRelation.Insert();

                    //初始化板块
                    SectionsFactory objSectionsFactory = new SectionsFactory(_DBManager);
                    //首页
                    BusinessLogic.BusinessRules.Sections objSections = objSectionsFactory.NewInstance();
                    objSections.DataItem.chvSTCName = "首页";
                    objSections.DataItem.chvSTEName = "Index";
                    objSections.DataItem.intParentID = 0;
                    objSections.DataItem.intArticleTemID = intBlankArticleTempID;
                    objSections.DataItem.intSectionTemID = intBlankSectionTempID;
                    objSections.DataItem.intState = Convert.ToInt32(Utility.STDisplay.Yes);
                    objSections.DataItem.intType = Convert.ToInt32(Utility.STType.Content);
                    objSections.DataItem.dtmInTime = DateTime.Now;
                    objSections.DataItem.intWSID = objWebSite.DataItem.intWebSiteID;
                    objSections.DataItem.txtSTMemo = "";
                    objSections.DataItem.chvContent = "";
                    objSections.DataItem.intDisplay = 1;
                    objSections.DataItem.intSortNo = 10000;
                    objSections.DataItem.chvSectionMainPic = "";
                    objSections.DataItem.chvFullPath = "";
                    objSections.DataItem.chvDescription = " ";
                    objSections.DataItem.txtSeodescription = " ";
                    objSections.DataItem.txtSeoKeywords = " ";
                    objSections.DataItem.txtSeoTitle = " ";
                    objSections.DataItem.intIssueState = (int)Utility.STIssueState.NoIssue;
                    objSections.Insert();
                    //其他设定
                    objSections = objSectionsFactory.NewInstance();
                    objSections.DataItem.chvSTCName = "其他设定";
                    objSections.DataItem.chvSTEName = "Other";
                    objSections.DataItem.intParentID = 0;
                    objSections.DataItem.intArticleTemID = intBlankArticleTempID;
                    objSections.DataItem.intSectionTemID = intBlankSectionTempID;
                    objSections.DataItem.intState = Convert.ToInt32(Utility.STDisplay.Yes);
                    objSections.DataItem.intType = Convert.ToInt32(Utility.STType.Content);
                    objSections.DataItem.dtmInTime = DateTime.Now;
                    objSections.DataItem.intWSID = objWebSite.DataItem.intWebSiteID;
                    objSections.DataItem.txtSTMemo = "";
                    objSections.DataItem.chvContent = "";
                    objSections.DataItem.intDisplay = 1;
                    objSections.DataItem.intSortNo = 0;
                    objSections.DataItem.chvSectionMainPic = "";
                    objSections.DataItem.chvFullPath = "";
                    objSections.DataItem.chvDescription = " ";
                    objSections.DataItem.txtSeodescription = " ";
                    objSections.DataItem.txtSeoKeywords = " ";
                    objSections.DataItem.txtSeoTitle = " ";
                    objSections.DataItem.intIssueState = (int)Utility.STIssueState.NoIssue;
                    objSections.Insert();
                    _DBManager.Commit();
                    if (State.LoginUser.LoginName != "FirstSysadmin")
                    {
                        AlertAndRedirectAndExecOther("新建网站成功", "../WebsiteManagerIndex.aspx", false, "window.parent.refrashleft();");
                    }
                    objSectionsFactory.Dispose();
                    objUserWebRelationFactory.Dispose();
                    objSystemVariableFactory.Dispose();
                    objTemplateFactory.Dispose();
                    objFactory.Dispose();

                    if (State.LoginUser.LoginName == "FirstSysadmin")
                    {
                        //清除当前Session对象
                        Session.Clear();
                        //清除当前Application对象
                        Application.Clear();
                        //清除登陆验证票据
                        System.Web.Security.FormsAuthentication.SignOut();
                        AlertAndExecOther("初始建站成功，即将注销，请重新登录！", "正在跳转至系统登陆页，请稍等……", " window.parent.location='" + System.Web.HttpContext.Current.Request.Path.Replace("ServerPages/SysManage/AddSebSite.aspx", "") + "login.aspx'");
                    }
                }
                catch (Exception ex)
                {
                    _DBManager.Rollback();
                    objLog.Error(ex.Message + ex.Source);
                    Alert(ex.Message);
                }
                finally
                {
                    _DBManager.Dispose();
                }
            }
        }
    }
}